package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    //微信登录服务接口
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) throws IOException {
        // 在调用微信接口前，添加日志
        log.info("当前小程序appid：{}", weChatProperties.getAppid());
        log.info("当前小程序secret：{}", weChatProperties.getSecret());  // 查看这个值是否为null
        //通过code从微信接口获取openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());  //配置属性类里面的配置信息 AppId
        map.put("secret",weChatProperties.getSecret()); //配置属性类里面的配置信息 Secret
        map.put("js_code",userLoginDTO.getCode()); //code
        map.put("grant_type","authorization_code");  //固定值
        //调用微信接口服务  获得 json数据包
        String json=HttpClientUtil.doGet(WX_LOGIN, map);  //调用的这个方法实际获得的值是 json数据包
        //解析json数据包    //调用JSONObject类 //将json数据包转换成JSONObject对象
        JSONObject jsonObject = JSONObject.parseObject(json);
        //直接通过get方法获取openid
        String openid = jsonObject.getString("openid");  //获取到openid
        log.info("openid为：{}", openid);
        //对openid进行判断
        if (openid == null) {
            //抛出登录失败的异常
            throw new RuntimeException(MessageConstant.LOGIN_FAILED);
        }
        //判断openid是否已经存在
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            //不存在  则插入数据
            // 正确代码：将builder创建的对象赋值给user
            user = User.builder()  // 注意这里是User.builder()静态方法，而非user.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            // 插入后获取自增ID（需确保mapper的insert方法支持返回自增ID）
            userMapper.insert(user);
            // 此时user的id已由MyBatis自动回填（无需手动setId）
        }
        log.info("微信登录成功，用户信息为：{}", user);

        //生成  jwt  令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey()
                , jwtProperties.getUserTtl()
                ,claims);
        //封装数据返回
        UserLoginVO userLoginVO = new UserLoginVO(user.getId(), user.getOpenid(), token);
        return userLoginVO;
    }
}
